package com.fqy.ticket.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.fqy.ticket.business.domain.TrainStation;
import com.fqy.ticket.business.domain.TrainStationExample;
import com.fqy.ticket.business.mapper.TrainStationMapper;
import com.fqy.ticket.business.req.TrainstationQueryReq;
import com.fqy.ticket.business.req.TrainstationSaveReq;
import com.fqy.ticket.business.resp.TrainstationQueryResp;
import com.fqy.ticket.common.exception.BusinessException;
import com.fqy.ticket.common.exception.BusinessExceptionEnum;
import com.fqy.ticket.common.resp.PageResp;
import com.fqy.ticket.common.util.SnowUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TrainstationService {

    private static final Logger LOG = LoggerFactory.getLogger(TrainstationService.class);

    @Resource
    private TrainStationMapper trainstationMapper;

    /**
     * 保存Trainstation记录（新增或更新）
     * @param req 保存请求对象
     */
    public void save(TrainstationSaveReq req) {
        DateTime now = DateTime.now();
        TrainStation trainstation = BeanUtil.copyProperties(req, TrainStation.class);

        if (ObjectUtil.isNull(trainstation.getId())) {
            // 保存之前，先校验唯一键是否存在
            TrainStation trainStationDB = selectByUnique(req.getTrainCode(), req.getIndex());
            if (ObjectUtil.isNotEmpty(trainStationDB)) {
                throw new BusinessException(BusinessExceptionEnum.BUSINESS_TRAIN_STATION_INDEX_UNIQUE_ERROR);
            }
            // 保存之前，先校验唯一键是否存在
            trainStationDB = selectByUnique(req.getTrainCode(), req.getName());
            if (ObjectUtil.isNotEmpty(trainStationDB)) {
                throw new BusinessException(BusinessExceptionEnum.BUSINESS_TRAIN_STATION_NAME_UNIQUE_ERROR);
            }
            // 新增逻辑
            trainstation.setId(SnowUtil.getSnowflakeNextId());
            trainstation.setCreateTime(now);
            trainstation.setUpdateTime(now);
            trainstationMapper.insert(trainstation);
            LOG.info("新增Trainstation成功，ID：{}", trainstation.getId());
        } else {
            // 更新逻辑
            trainstation.setUpdateTime(now);
            trainstationMapper.updateByPrimaryKey(trainstation);
        }
    }

    /**
     * 分页查询Trainstation列表
     * @param req 查询请求对象（包含分页信息）
     * @return 分页结果
     */
    public PageResp<TrainstationQueryResp> queryList(TrainstationQueryReq req) {
        TrainStationExample trainstationExample = new TrainStationExample();
        trainstationExample.setOrderByClause("train_code asc, `index` asc");
        TrainStationExample.Criteria criteria = trainstationExample.createCriteria();

        if (ObjectUtil.isNotEmpty(req.getTrainCode())) {
            criteria.andTrainCodeEqualTo(req.getTrainCode());
        }

        LOG.info("查询Trainstation列表，页码：{}，每页条数：{}", req.getPage(), req.getSize());
        PageHelper.startPage(req.getPage(), req.getSize());
        List<TrainStation> trainStationList = trainstationMapper.selectByExample(trainstationExample);

        PageInfo<TrainStation> pageInfo = new PageInfo<>(trainStationList);
        LOG.info("查询结果：总行数={}，总页数={}", pageInfo.getTotal(), pageInfo.getPages());

        List<TrainstationQueryResp> list = BeanUtil.copyToList(trainStationList, TrainstationQueryResp.class);

        PageResp<TrainstationQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    /**
     * 根据ID删除Trainstation记录
     * @param id 记录ID
     */
    public void delete(Long id) {
        int count = trainstationMapper.deleteByPrimaryKey(id);
    }

    private TrainStation selectByUnique(String trainCode, Integer index) {
        TrainStationExample example = new TrainStationExample();
        TrainStationExample.Criteria criteria = example.createCriteria();
        criteria.andTrainCodeEqualTo(trainCode).andIndexEqualTo(index);
        List<TrainStation> list = trainstationMapper.selectByExample(example);
        return CollUtil.isEmpty(list) ? null : list.get(0);
    }
    private TrainStation selectByUnique(String trainCode, String name) {
        TrainStationExample example = new TrainStationExample();
        TrainStationExample.Criteria criteria = example.createCriteria();
        criteria.andTrainCodeEqualTo(trainCode).andNameEqualTo(name);
        List<TrainStation> list = trainstationMapper.selectByExample(example);
        return CollUtil.isEmpty(list) ? null : list.get(0);
    }
}